﻿using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

using SRM.Core.Models;

using System.Linq;

namespace SRM.DataAccess
{
    public class AppDbContext : IdentityDbContext<ApplicationUser>
    {
        public AppDbContext(DbContextOptions<AppDbContext> dbContextOptions) : base(dbContextOptions)
        {
        }

        public DbSet<PurchaseOrder> PurchaseOrders { get; set; }

        public DbSet<PurchaseOrderDetail> PurchaseOrderDtl { get; set; }

        public DbSet<ReturnOrder> ReturnOrders { get; set; }

        public DbSet<ReturnOrderDetail> ReturnOrderDtl { get; set; }

        public DbSet<DeliverOrder> DeliverOrders { get; set; }

        public DbSet<DeliverOrderDetail> DeliverOrderDtl { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<PurchaseOrder>().ToTable(nameof(PurchaseOrder)).HasKey(c => c.Id);
            modelBuilder.Entity<PurchaseOrderDetail>().ToTable(nameof(PurchaseOrderDetail)).HasKey(c => c.Id);
            modelBuilder.Entity<ReturnOrder>().ToTable(nameof(ReturnOrder)).HasKey(c => c.Id);
            modelBuilder.Entity<ReturnOrderDetail>().ToTable(nameof(ReturnOrderDetail)).HasKey(c => c.Id);
            modelBuilder.Entity<DeliverOrder>().ToTable(nameof(DeliverOrder)).HasKey(c => c.Id);
            modelBuilder.Entity<DeliverOrderDetail>().ToTable(nameof(DeliverOrderDetail)).HasKey(c => c.Id);

            //获取所有表的外键列表
            var foreignKeys =
               modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys());

            foreach (var foreignKey in foreignKeys)
            {
                //将他们的删除行为配置为 Restrict ，即无操作
                foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
            }
        }
    }
}
